﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using MODEL;
using MySql.Data.MySqlClient;
using Common;

namespace DAL
{
    public class MessageInfoDAL
    {
        public static async Task<IEnumerable<MessageInfo>> QueryMessageInfosAsync(MessageInfoQueryCriteria criteria)
        {
            MessageInfoQueryCriteria queryCriteria = criteria == null ? new MessageInfoQueryCriteria() : criteria;

            string sql = $@"SELECT id
                        , userId
                        , receiver
                        , title
                        , content
                        , `timestamp` 
                        from msap_db.message
                        WHERE
                        (@UserId is null OR userId = @UserId)
                        AND (@Receiver is null OR receiver = @Receiver OR receiver like @ReceiverMatch1
                        OR receiver like @ReceiverMatch2)
                        AND (@BeginDate is null OR `timestamp` > @BeginDate)
                        AND (@EndDate is null OR `timestamp` < @EndDate)
                        UNION all
                        SELECT alertId as id
                        ,addMan AS userId
                        ,userIds AS receiver
                        ,alertName AS title
                        ,alertContext AS content
                        ,createTime AS `timestamp`
                        FROM msap_db.alert_infor
                        WHERE 
                         (@UserId is null OR addMan = @UserId)
                        AND (@Receiver is null OR userIds = @Receiver OR userIds like @ReceiverMatch1
                        OR userIds like @ReceiverMatch2)
                        AND (@BeginDate is null OR createTime > @BeginDate)
                        AND (@EndDate is null OR createTime < @EndDate)";
            using (MySqlConnection conn = new MySqlConnection(AppSetting.Instance.MySqlConnectionStr))
            {
                return await conn.QueryAsync<MessageInfo>(sql, new {
                    UserId = queryCriteria.UserId.ChangeEmptyToNull(),
                    Receiver = queryCriteria.Receiver.ChangeEmptyToNull(),
                    ReceiverMatch1 = string.IsNullOrEmpty(queryCriteria.Receiver)? null:$"%,{queryCriteria.Receiver}%",
                    ReceiverMatch2 = string.IsNullOrEmpty(queryCriteria.Receiver) ? null : $"%{queryCriteria.Receiver},%",
                    BeginDate = queryCriteria.BeginDate.ChangeEmptyToNull(),
                    EndDate = queryCriteria.EndDate.ChangeEmptyToNull()
                });
            }
        }

        public static Task<int> InsertMessage(MessageInfo messageInfo, MessageReleaseType messageReleaseType)
        {
            string sql = string.Empty;

            switch (messageReleaseType)
            {
                case MessageReleaseType.MessageRelease:
                    sql = @"INSERT INTO msap_db.message
                            (
                                Id
                                ,userId
                                , receiver
                                , title
                                , content
                                , `timestamp`
                            )
                            values
                            (
                                @Id
                                ,@UserId
                                , @Receiver
                                , @Title
                                , @Content
                                , now()
                            )";
                    break;

                case MessageReleaseType.UserAlert:
                case MessageReleaseType.NormalAlert:
                    sql = @"INSERT INTO msap_db.alert_infor
                            (
                                make_recordId
                                ,addMan
                                , userIds
                                , alertName
                                , alertContext
                                , createTime
                            )
                            values
                            (
                                @MakeRecordId
                                ,@UserId
                                , @Receiver
                                , @Title
                                , @Content
                                , now()
                            )";
                    break;
                default:
                    throw new Exception("没有这种消息类型");
            }

            string id = Guid.NewGuid().ToString();
            using (MySqlConnection conn = new MySqlConnection(AppSetting.Instance.MySqlConnectionStr))
            {
                return conn.ExecuteAsync(sql, new {
                    Id = Guid.NewGuid().ToString(),
                    UserId = AppSetting.Instance.User.UserId,
                    MakeRecordId = messageInfo.AlertMakeRecord?.Id,
                    Receiver = messageInfo.Receiver,
                    Title = messageInfo.Title,
                    Content = messageInfo.Content
                });
            }
        }
    }
}
